package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.sysstation.*;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.entity.config.SysDictionaryConfig;
import com.qingcloud.adminbackend.entity.domain.SysDomain;
import com.qingcloud.adminbackend.entity.equipment.EquipmentBO;
import com.qingcloud.adminbackend.entity.equipment.ModelDTO;
import com.qingcloud.adminbackend.entity.equipment.SysEquipment;
import com.qingcloud.adminbackend.entity.stationequipment.OptStationEquipment;
import com.qingcloud.adminbackend.entity.stationgroup.SysOrgStationGroup;
import com.qingcloud.adminbackend.entity.stationgroup.SysStationGroupEquipment;
import com.qingcloud.adminbackend.entity.sysorder.SysOrder;
import com.qingcloud.adminbackend.entity.sysorder.SysOrderEquipment;
import com.qingcloud.adminbackend.entity.sysorg.SysUserOrgMgr;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.entity.sysstationmo.SysStationMo;
import com.qingcloud.adminbackend.entity.sysstationmo.SysStationMoAddress;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.enums.StationStatus;
import com.qingcloud.adminbackend.service.ISysStationService;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.adminbackend.utils.DateUtil;
import com.qingcloud.adminbackend.utils.ExcelUtil;
import com.qingcloud.adminbackend.utils.StringUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 监测点信息表 服务实现类
 * </p>
 *
 * @author luozehua
 * @since 2019-04-10
 */
@Service
public class SysStationServiceImpl extends ServiceImpl<SysStationMapper, SysStation> implements ISysStationService {

    private static final Integer PROID = 1;
    private static final Integer CITYID = 2;
    private static final Integer DISTID = 3;
    private static final Integer STREET = 4;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SysStationServiceImpl.class);
    @Resource
    private SysStationMapper sysStationMapper;

    @Resource
    private SysStationBackupMapper sysStationBackupMapper;
    @Resource
    private SysStationEquipmentMapper sysStationEquipmentMapper;
    @Resource
    private SysStationImagesMapper sysStationImagesMapper;
    @Resource
    private SysOrderEquipmentMapper sysOrderEquipmentMapper;
    @Resource
    private SysStationShareTimeMapper sysStationShareTimeMapper;
    @Resource
    private SysOrderMapper sysOrderMapper;
    @Resource
    private SysStationMoMapper sysStationMoMapper;
    @Resource
    private SysOrgStationGroupMapper sysOrgStationGroupMapper;
    @Resource
    private SysStationGroupEquipmentMapper sysStationGroupEquipmentMapper;
    @Resource
    private SysDomainMapper sysDomainMapper;
    @Resource
    private SysDictionaryConfigMapper sysDictionaryConfigMapper;
    @Resource
    private SysEquipmentMapper sysEquipmentMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysStationMoAddressMapper sysStationMoAddressMapper;

    @Resource

//    @Resource
//    private TdWcenterThresholdDefaultMapper thresholdDefaultMapper
    private SysUserOrgMgrMapper sysUserOrgMgrMapper;;
//
//    @Resource
//    private TdWcenterThresholdMapper thresholdMapper;


    /**
     * 展示监测点详情
     *
     * @param stationId
     */
    @Override
    public StationDetailsDTO details(String stationId, String userId, boolean isAdmin) {
        StationDetailsDTO details = sysStationMapper.details(stationId);
        if (details != null) {
            String shareDate = details.getShareDate();
            String startTime = details.getStartTime();
            String endTime = details.getEndTime();
            details.setShareDateTimeDesc(dateTimeDesc(shareDate, startTime, endTime, false));
            String moId = details.getMoId();
            if (StrUtil.isNotBlank(moId)) {
                int length = moId.length();
                String tempCapation = "";
                String tempCapationId = "";
                String address = "-1";
                for (int i = 0; i < length / 5; i++) {
                    String tempId = moId.substring(0, 5 * (i + 1));
                    SysStationMo mo = sysStationMoMapper.selectById(tempId);
                    if (mo != null) {
                        if (i == 0) {
                            address = mo.getAddress();
                            details.setBuild(mo.getCapation());
                            details.setBuildId(mo.getId());
                            details.setShowType(mo.getShowType());
                        } else if (i == 1) {
                            String floorId = moId.substring(0, 10);
                            SysStationMo floor = sysStationMoMapper.selectById(floorId);
                            details.setFloor(floor.getCapation());
                            details.setFloorId(mo.getId());
                            details.setShowType(mo.getShowType());
                        } else if (i == 2) {
                            String roomId = moId.substring(0, 15);
                            SysStationMo room = sysStationMoMapper.selectById(roomId);
                            details.setRoom(room.getCapation());
                            details.setRoomId(mo.getId());
                            details.setShowType(mo.getShowType());
                        }
                        tempCapation += mo.getCapation().concat("-");
                        tempCapationId += mo.getId().concat("-");
                    }
                }
                if (StrUtil.isNotBlank(tempCapation)) {
                    details.setPosition(tempCapation.substring(0, tempCapation.length() - 1));
                }
                if (StrUtil.isNotBlank(tempCapationId)) {
                    details.setPositionId(tempCapationId.substring(0, tempCapationId.length() - 1));
                }
                SysStationMoAddress sysStationMoAddress = sysStationMoAddressMapper.selectById(address);
                if (sysStationMoAddress != null) {
                    details.setHealthStreetName(sysStationMoAddress.getCapation());
                }
            }
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser.getAdminFlag();
        if (adminFlag == 1) {
            isAdmin = true;
        }
        //获取登录用户有管理权限的订单
        List<String> orderIds = getManageOrderId(userId, isAdmin);
        if (isAdmin || (CollUtil.isNotEmpty(orderIds) && orderIds.contains(details.getOrderId()))) {
            details.setManageAuth(1);
        } else {
            details.setManageAuth(0);
        }
        return details;
    }

    private List<String> getManageOrderId(String userId, boolean isAdmin) {
        List<String> orderIds = new ArrayList<>();
        if (isAdmin) {
            List<SysOrder> sysOrders = sysOrderMapper.selectByMap(ImmutableMap.of("business_type", 2, "delete_flag", 0));
            sysOrders.forEach(t -> orderIds.add(t.getId()));
        } else {
            //查询用户能管理的客户
            List<SysUserOrgMgr> sysUserOrgMgrs = sysUserOrgMgrMapper.selectByMap(ImmutableMap.of("user_id", userId, "manage", 1));
            List<String> orgIds = sysUserOrgMgrs.stream().map(SysUserOrgMgr::getOrgId).collect(Collectors.toList());
            //订单
            List<String> orderIdList = sysOrderMapper.getAllManageOrderId(userId);
            orderIds.addAll(orderIdList);
            if (CollUtil.isNotEmpty(orgIds)) {
                QueryWrapper<SysOrder> query = new QueryWrapper<>();
                query.in("org_id", orgIds);
                query.eq("business_type", 2);
                query.eq("delete_flag", 0);
                List<SysOrder> sysOrders = sysOrderMapper.selectList(query);
                sysOrders.forEach(t -> orderIds.add(t.getId()));
            }
        }
        return orderIds;
    }

    /**
     * 批量删除
     *
     * @param stationIds
     * @return
     */
    @Override
    @Transactional
    public int delete(List<String> stationIds, String userId) {
        if (CollUtil.isEmpty(stationIds)) {
            return 0;
        }
        stationIds.forEach(s -> {
            //判断是否有绑定设备
            QueryWrapper<SysStationEquipment> query = new QueryWrapper<>();
            query.eq("station_id", s);
            query.in("mount_status", 1, 2);
            Long count = sysStationEquipmentMapper.selectCount(query);
            if (count > 0) {
                //解除绑定
                SysStationEquipment sse = new SysStationEquipment();
                sse.setMountStatus(0);
                sse.setOperateBy(userId);
                sse.setUnbindTime(DateUtil.getCurrentDateTime());
                QueryWrapper<SysStationEquipment> query2 = new QueryWrapper<>();
                query2.eq("station_id", s);
                query2.in("mount_status", 1, 2);
                sysStationEquipmentMapper.update(sse, query2);

            }
            QueryWrapper<SysOrderEquipment> querySe = new QueryWrapper<>();
            querySe.eq("station_id", s);
            SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(querySe);
            if (StrUtil.isBlank(sysOrderEquipment.getEquipmentId())) {
                //监测点是空的，则删除这个数据
                sysOrderEquipmentMapper.delete(querySe);
            } else {
                //订单解除
                SysOrderEquipment soe = new SysOrderEquipment();
                soe.setStationId("");
                soe.setModifyBy(userId);
                soe.setModifyDt(new Date());
                QueryWrapper<SysOrderEquipment> query3 = new QueryWrapper<>();
                query3.eq("station_id", s);
                sysOrderEquipmentMapper.update(soe, query3);
            }
            //删除站点信息/ 新增到备份表
            QueryWrapper<SysStation> stationQueryWrapper = new QueryWrapper<>();
            stationQueryWrapper.eq("station_id", s);
            SysStation sysStation = sysStationMapper.selectOne(stationQueryWrapper);
            if (null == sysStation) {
                throw new WmCommonException("获取" + s + "站点信息异常！");
            }
            SysStationBackup backup = new SysStationBackup();
            BeanUtil.copyProperties(sysStation, backup);
            backup.setDeleteFlag(1);
            sysStationBackupMapper.insert(backup);
            sysStationMapper.delete(stationQueryWrapper);
//            sysStationMapper.logicDelete(s);
            //删除图片
            sysStationImagesMapper.deleteByMap(ImmutableMap.of("station_id", s));
            //删除共享时间
            sysStationShareTimeMapper.deleteByMap(ImmutableMap.of("station_id", s));
            //设备组中数据
            sysStationGroupEquipmentMapper.deleteByBindStation(s);
            sysStationGroupEquipmentMapper.updateByBindStation(s);
        });
        return 1;
    }

    /**
     * 上线监测点
     *
     * @param stationIds
     */
    @Override
    @Transactional
    public void online(List<String> stationIds) {
        sysStationMapper.updateStatus(stationIds, StationStatus.ONLINE.getCode());
    }

    /**
     * 下线监测点
     *
     * @param stationIds
     */
    @Override
    @Transactional
    public void offline(List<String> stationIds) {
        sysStationMapper.updateStatus(stationIds, StationStatus.OFFLINE.getCode());
    }

    /**
     * 新业务设置共享
     *
     * @param stationShareTimeDTO
     */
    @Override
    @Transactional
    public Integer share(StationShareTimeDTO stationShareTimeDTO, String userId) {
        List<String> stationIds = stationShareTimeDTO.getStationIds();
        if (CollUtil.isEmpty(stationIds)) {
            return 0;
        }
        Integer status = stationShareTimeDTO.getStatus();
        sysStationMapper.setShare(stationIds, status);
        //删除原有的设置
        QueryWrapper<SysStationShareTime> deleteQuery = new QueryWrapper();
        deleteQuery.in("station_id", stationIds);
        sysStationShareTimeMapper.delete(deleteQuery);
        if (WamingConstant.ONE.equals(status)) {
            //设置成共享
            List<String> shareDates = stationShareTimeDTO.getShareDates();
            String weeks = shareDates.stream().collect(Collectors.joining(","));
            String startTime = stationShareTimeDTO.getStartTime();
            String endTime = stationShareTimeDTO.getEndTime();
            stationIds.forEach(s -> {
                SysStationShareTime share = new SysStationShareTime();
                share.setStationId(s);
                share.setStartTime(startTime);
                share.setEndTime(endTime);
                share.setShareDate(weeks);
                share.setCreateDt(new Date());
                share.setCreateBy(userId);
                sysStationShareTimeMapper.insert(share);
            });
        }
        return 1;
    }

    /**
     * 根据站点ID查询所选站点的共享信息
     *
     * @param shareStationPageDTO
     * @return
     */
    @Override
    public IPage<StationShareDTO> selectShareByPage(ShareStationPageDTO shareStationPageDTO) {
        Page<StationShareDTO> page = new Page<>(shareStationPageDTO.getCurrentPage(), shareStationPageDTO.getPerPage());
        return sysStationMapper.selectShareByPage(page, shareStationPageDTO.getStationIds());
    }

    @Override
    public List<StationShare> selectShare(List<String> stationIds) {
        List<StationShare> result = new ArrayList<>();
        List<StationShareDTO> stationShareDTOS = sysStationMapper.selectShare(stationIds);
        stationShareDTOS.forEach(s -> {
            StationShare temp = new StationShare();
            temp.setShared(s.getShared());
            temp.setSharedStr(s.getSharedStr());
            temp.setStationId(s.getStationId());
            temp.setStationName(s.getStationName());
            temp.setShareDateTimeDesc(dateTimeDesc(s.getSharedDates(), s.getStartTime(), s.getEndTime(), true));
            result.add(temp);
        });
        return result;
    }

    /**
     * 处理共享时间描述
     *
     * @param sharedDates
     * @param startTime
     * @param endTime
     * @return
     */
    private String dateTimeDesc(String sharedDates, String startTime, String endTime, Boolean isLindFeed) {
        String timeStr = "";
        String weekStr = "";
        if (StrUtil.isNotBlank(sharedDates)) {
            String[] temp = sharedDates.split(",");
            if (ArrayUtil.isNotEmpty(temp)) {
                List<String> weeks = Arrays.asList(temp);
                Collections.sort(weeks);
                String tempStr = String.join(",", weeks);
                //星期
                weekStr = getDayDesc(weeks, tempStr);
                //开始结束时间
                if (WamingConstant.STATTIME.equals(startTime) && WamingConstant.ENDTIME.equals(endTime)) {
                    timeStr = "全天";
                } else {
                    timeStr = timeStr.concat(startTime).concat("~").concat(endTime);
                }
                if (StrUtil.isNotBlank(weekStr) && StrUtil.isNotBlank(timeStr)) {
                    if (isLindFeed) {
                        return weekStr.concat("<br/>").concat(timeStr);
                    } else {
                        return weekStr.concat("&nbsp;&nbsp;&nbsp;").concat(timeStr);
                    }
                }
            }
        }
        return StrUtil.EMPTY;
    }

    private String exportDateTimeDesc(String sharedDates, String startTime, String endTime) {
        String timeStr = "";
        String weekStr = "";
        if (StrUtil.isNotBlank(sharedDates)) {
            String[] temp = sharedDates.split(",");
            if (ArrayUtil.isNotEmpty(temp)) {
                List<String> weeks = Arrays.asList(temp);
                Collections.sort(weeks);
                String tempStr = String.join(",", weeks);
                //星期
                weekStr = getDayDesc(weeks, tempStr);
                //开始结束时间
                if (WamingConstant.STATTIME.equals(startTime) && WamingConstant.ENDTIME.equals(endTime)) {
                    timeStr = "全天";
                } else {
                    timeStr = timeStr.concat(startTime).concat("~").concat(endTime);
                }
                if (StrUtil.isNotBlank(weekStr) && StrUtil.isNotBlank(timeStr)) {
                    return weekStr.concat(" ").concat(timeStr);
                }
            }
        }
        return StrUtil.EMPTY;
    }

    private String getDayDesc(List<String> weeks, String tempStr) {
        String weekStr;
        if (tempStr.equals("1,2,3,4,5,6,7")) {
            weekStr = "每天";
        } else if (tempStr.equals("1,2,3,4,5,6")) {
            weekStr = "周一至周六";
        } else if (tempStr.equals("1,2,3,4,5")) {
            weekStr = "周一至周五";
        } else if (tempStr.equals("1,2,3,4")) {
            weekStr = "周一至周四";
        } else if (tempStr.equals("1,2,3")) {
            weekStr = "周一至周三";
        } else if (tempStr.equals("2,3,4,5,6,7")) {
            weekStr = "周二至周日";
        } else if (tempStr.equals("2,3,4,5,6")) {
            weekStr = "周二至周六";
        } else if (tempStr.equals("2,3,4,5")) {
            weekStr = "周二至周五";
        } else if (tempStr.equals("2,3,4")) {
            weekStr = "周二至周四";
        } else if (tempStr.equals("3,4,5,6,7")) {
            weekStr = "周三至周日";
        } else if (tempStr.equals("3,4,5,6")) {
            weekStr = "周三至周六";
        } else if (tempStr.equals("3,4,5")) {
            weekStr = "周三至周五";
        } else if (tempStr.equals("4,5,6,7")) {
            weekStr = "周四至周日";
        } else if (tempStr.equals("4,5,6")) {
            weekStr = "周四至周六";
        } else if (tempStr.equals("5,6,7")) {
            weekStr = "周五至周日";
        } else {
            weekStr = translateWeek(weeks);
        }
        return weekStr;
    }

    private String translateWeek(List<String> weeks) {
        List<String> temp = new ArrayList<>();
        weeks.forEach(w -> {
            switch (w) {
                case WamingConstant.MONDAY:
                    temp.add("周一");
                    break;
                case WamingConstant.TUESDAY:
                    temp.add("周二");
                    break;
                case WamingConstant.WEDNESDAY:
                    temp.add("周三");
                    break;
                case WamingConstant.THURSDAY:
                    temp.add("周四");
                    break;
                case WamingConstant.FRIDAY:
                    temp.add("周五");
                    break;
                case WamingConstant.SATURDAY:
                    temp.add("周六");
                    break;
                case WamingConstant.SUNDAY:
                    temp.add("周日");
                    break;
                default:
                    break;
            }
        });
        if (CollUtil.isEmpty(temp)) {
            return StrUtil.EMPTY;
        }
        String join = String.join("&nbsp;", temp);
        return join;
    }

    /**
     * 绑定设备获取绑定信息
     *
     * @param stationId
     * @return
     */
    @Override
    public Map<String, Object> mount(String stationId) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<SysStation> stationQueryWrapper = new QueryWrapper<>();
        stationQueryWrapper.eq("station_id", stationId);
        StationDetailsDTO details = sysStationMapper.details(stationId);

        List<MountStationInfo> mountStationInfos = sysStationMapper.getMountInfo(stationId);
        if (mountStationInfos.size() == 1 && null == mountStationInfos.get(0).getProductType()) {
            return null;
        }
        for (MountStationInfo stationInfo : mountStationInfos) {
            if (null != stationInfo.getProductType()) {
                if (stationInfo.getProductType().equals(RobotServiceImpl.robotProduct)) {
                    stationInfo.setType(1);
                } else {
                    stationInfo.setType(2);
                }
            }
        }
        map.put("stationInfo", details);
        map.put("stationEquipment", mountStationInfos);
        return map;
    }

    /**
     * 批量绑定设备
     *
     * @param excelFile
     * @param userId
     * @return
     */
    @Override
    public AjaxResult batchMount(MultipartFile excelFile, Integer businessType, String userId, Boolean isAdmin) {
        //这里有个疑问，是否是人为控制这个监测点是属于哪个订单
        List<BacthBindStation> result = new ArrayList<>();
        try (InputStream inputStream = excelFile.getInputStream()) {
            if (!(FileMagic.valueOf(inputStream) == FileMagic.OOXML)) {
                //请上传excel xlsx类型文件，建议使用官方提供的模板;
                return new AjaxResult(WamingConstant.PART_SUCCESS, "请上传excel xlsx类型文件，建议使用官方提供的模板", "");
            }
            //解析excel
            XSSFWorkbook workbook2007 = new XSSFWorkbook(excelFile.getInputStream());
            // 取得第一个sheet
            XSSFSheet sheet = workbook2007.getSheetAt(0);
            // 多少行
            int count = sheet.getPhysicalNumberOfRows();
            if (count < 1) {
                //Excel文件内容是空的
                return new AjaxResult(WamingConstant.PART_SUCCESS, "Excel文件内容是空的", "");
            }
            XSSFCell cell;
            for (int i = 1; i < count; i++) {
                // 获取行对象
                XSSFRow row = sheet.getRow(i);
                if (row == null) {// 如果为空，不处理
                    continue;
                }
                //监测点编号
                cell = row.getCell(0);
                String stationId = null;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stationId = cell.getStringCellValue().trim();
                }
                //设备编号
                cell = row.getCell(1);
                String equipmentId = null;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    equipmentId = cell.getStringCellValue().trim();
                }
                //监测点状态
                cell = row.getCell(2);
                String statusStr = null;
                Integer status = -1;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    statusStr = cell.getStringCellValue().trim();
                    if (WamingConstant.STATION_STATION_NORMAL.equals(statusStr)) {
                        status = 1;
                    }
                }
                int rowNum = row.getRowNum() + 1;
                //判断监测点或者设备编号是否还存在
                List<SysStation> sysStations = sysStationMapper.selectByMap(ImmutableMap.of("station_id", stationId, "delete_flag", 0));
                if (CollUtil.isEmpty(sysStations)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行监测点" + stationId + "不存在", "");
                }
                List<SysEquipment> sysEquipments = sysEquipmentMapper.selectByMap(ImmutableMap.of("equipment_id", equipmentId, "delete_flag", 0));
                if (CollUtil.isEmpty(sysEquipments)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行设备" + equipmentId + "不存在", "");
                }

                if (StrUtil.isBlank(stationId) && StrUtil.isBlank(equipmentId) && StrUtil.isBlank(statusStr)) {
                    //这一行都是空的
                    continue;
                } else if (StrUtil.isBlank(stationId) && StrUtil.isNotBlank(equipmentId) && StrUtil.isNotBlank(statusStr)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行监测点编号为空", "");
                } else if (StrUtil.isNotBlank(stationId) && StrUtil.isBlank(equipmentId) && StrUtil.isNotBlank(statusStr)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行设备编号为空", "");
                } else if (StrUtil.isNotBlank(stationId) && StrUtil.isNotBlank(equipmentId) && StrUtil.isBlank(statusStr)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行监测点状态为空", "");
                }
                BacthBindStation temp = new BacthBindStation();
                temp.setEquipmentId(equipmentId);
                temp.setStationId(stationId);
                temp.setStationStatus(status);
                String osid = sysOrderEquipmentMapper.findOrderIdByStationId(stationId);
                String oeid = sysOrderEquipmentMapper.findOrderIdByEquipmentId(equipmentId);
                //获取登录用户有些权限的订单
                List<String> manageOrderId = getManageOrderId(userId, isAdmin);
                if (StrUtil.isNotBlank(osid) && !manageOrderId.contains(osid)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行,您对该监测点所属订单没有管理权限!", "");
                } else if (StrUtil.isNotBlank(oeid) && !manageOrderId.contains(oeid)) {
                    return new AjaxResult(WamingConstant.PART_SUCCESS, "第" + rowNum + "行,您对该设备所属订单没有管理权限!", "");
                } else {
                    temp.setStationOrderId(osid);
                    temp.setEquipmentOrderId(oeid);
                }
                result.add(temp);
            }
            //检查检测点或者设备是否重复
            List<String> stationIds = result.stream().map(BacthBindStation::getStationId).collect(Collectors.toList());
            Set<String> stationSet = new HashSet<>(stationIds);
            if (stationIds.size() > stationSet.size()) {
                // 监测点重复
                return new AjaxResult(WamingConstant.PART_SUCCESS, "监测点重复", "");
            }
            List<String> equipmentIds = result.stream().map(BacthBindStation::getEquipmentId).collect(Collectors.toList());
            Set<String> equipmentIdSet = new HashSet<>(equipmentIds);
            if (equipmentIds.size() > equipmentIdSet.size()) {
                //设备重复
                return new AjaxResult(WamingConstant.PART_SUCCESS, "设备重复", "");
            }
            if (CollUtil.isNotEmpty(result)) {
                for (BacthBindStation bbs : result) {
                    String stationId = bbs.getStationId();
                    String equipmentId = bbs.getEquipmentId();
                    //2.监测点和设备在同一个订单内。
                    String osid = bbs.getStationOrderId();
                    String oeid = bbs.getEquipmentOrderId();
                    if ((StrUtil.isBlank(osid) || StrUtil.isBlank(oeid) || !StrUtil.equals(oeid, osid))) {
                        return new AjaxResult(WamingConstant.PART_SUCCESS, "监测点和设备不在同一个订单内", "");
                    }
                    SysOrder os = sysOrderMapper.findOrderById(osid);
                    SysOrder oe = sysOrderMapper.findOrderById(oeid);
                    if (!os.getBusinessType().equals(businessType) || !oe.getBusinessType().equals(businessType)) {
                        //业务类型不对
                        return new AjaxResult(WamingConstant.PART_SUCCESS, "业务类型不正确", "");
                    }
                    //3.监测点和设备都处在无绑定状态。
                    Integer smount = sysStationEquipmentMapper.findBandStatusByStationId(stationId);
                    Integer emount = sysStationEquipmentMapper.findBandStatusByEquipmentId(equipmentId);
                    if (smount > 0 || emount > 0) {
                        return new AjaxResult(WamingConstant.PART_SUCCESS, "监测点或者设备处在绑定状态", "");
                    }
                }
                for (BacthBindStation bbs : result) {
                    String stationId = bbs.getStationId();
                    String equipmentId = bbs.getEquipmentId();
                    //绑定设备
                    OptStationEquipment bindObj = new OptStationEquipment();
                    bindObj.setEquipmentId(equipmentId);
                    bindObj.setStationId(stationId);
                    bindObj.setOperateTime(DateUtil.getCurrentDateTime());
                    bindObj.setOperateBy(userId);
                    bindObj.setStationStatus(WamingConstant.ONE);
                    sysStationEquipmentMapper.bind(bindObj);
                    //修改last
                    sysStationEquipmentMapper.updateIsLast(bindObj.getId(), stationId);

                    //绑定成功后，更新监测点状态。
                    if (bbs.getStationStatus() == 1) {
                        sysStationMapper.updateStatus(Arrays.asList(stationId), WamingConstant.ONE);
                    }
                    //订单设备表数据清理
                    SysOrderEquipment soe = new SysOrderEquipment();
                    soe.setEquipmentId(equipmentId);
                    soe.setModifyBy(userId);
                    soe.setModifyDt(new Date());
                    QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
                    query.eq("station_id", stationId);
                    sysOrderEquipmentMapper.update(soe, query);
                    //删除多余的设备数据
                    sysOrderEquipmentMapper.deleteByBind(equipmentId);
                }
            } else {
                return new AjaxResult(WamingConstant.PART_SUCCESS, "Excel文件内容是空的", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(WamingConstant.PART_SUCCESS, "出现未知错误", "");
        }
        return new AjaxResult(WamingConstant.SUCCESS, "", "绑定设备成功");
    }

    /**
     * 添加检测点
     *
     * @param addStationDTO
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Integer addStation(AddStationDTO addStationDTO, String userId) {
        //添加基础信息
        SysStation station = new SysStation();
        station.setStationName(addStationDTO.getStationName());
        station.setStationNameEn(addStationDTO.getStationNameEn());
        station.setStationId(addStationDTO.getStationId());
        station.setStationCatagory(addStationDTO.getStationCatagory());
        station.setPro(addStationDTO.getPro());
        station.setCity(addStationDTO.getCity());
        station.setDistrict(addStationDTO.getDistrict());
        station.setStreet(addStationDTO.getStreet());
        station.setAddr(addStationDTO.getAddr());
        station.setLatReal(addStationDTO.getLatReal());
        station.setLngReal(addStationDTO.getLngReal());
        station.setMoId(addStationDTO.getMoId());

        Integer workType = addStationDTO.getWorkType();
        station.setWorkType(workType);
        //健康空气
        station.setLeftPx(addStationDTO.getLeftPx());
        station.setTopPx(addStationDTO.getTopPx());
        station.setLeftPxVertical(addStationDTO.getLeftPxVertical());
        station.setTopPxVertical(addStationDTO.getTopPxVertical());
        station.setLineHorizontal(addStationDTO.getLineHorizontal());
        station.setLineVertical(addStationDTO.getLineVertical());
        /*设置共享*/
        station.setShared(addStationDTO.getShared());
        station.setAmmeterNo(addStationDTO.getAmmeterNo());
        station.setPoleId(addStationDTO.getPoleId());
        station.setMark(addStationDTO.getMark());
        station.setStationType(addStationDTO.getStationType());
        //监测改订单是否被删除
        QueryWrapper<SysOrder> orderQuery = new QueryWrapper();
        orderQuery.eq("id", addStationDTO.getOrderId());
        orderQuery.eq("delete_flag", 0);
        Long count = sysOrderMapper.selectCount(orderQuery);
        if (count <= 0) {
            return -5;
        }
        if (addStationDTO.getId() == null) {

            String stationId = addStationDTO.getStationId();
            List<SysStation> sysStations = baseMapper.selectByMap(ImmutableMap.of("station_id", stationId, "delete_flag", 0));
            if (!CollUtil.isEmpty(sysStations)) {
                return -4;
            }
            //新增
            int ins = insert(addStationDTO, userId, station);
            return ins > 0 ? 2 : -2;

        } else {
            //修改
            int upd = update(addStationDTO, userId, station);
            return upd > 0 ? 3 : -3;
        }
    }

//    private void setRoadName(SysStation station, String streetName, String domainId) {
//        if (StrUtil.isNotBlank(streetName)) {
//            //查询插入街道
//            QueryWrapper<SysStationMoAddress> query = new QueryWrapper<>();
//            query.eq("capation", streetName);
//            query.eq("domain_id", domainId);
//            SysStationMoAddress address = sysStationMoAddressMapper.selectOne(query);
//            if (address != null) {
//                //已经存在
//                station.setStreetNo(address.getId());
//            } else {
//                SysStationMoAddress steet = new SysStationMoAddress();
//                String newStreetId = UUID.randomUUID().toString().replace("-", "");
//                steet.setId(newStreetId);
//                steet.setCapation(streetName);
//                steet.setDomainId(domainId);
//                sysStationMoAddressMapper.insert(steet);
//                station.setStreetNo(newStreetId);
//            }
//        }
//    }

    @Override
    public IPage<StationListDTO> listStation(StationListPara stationListPara, List<ModelDTO> stationData, String userId) {


        SysUser sysUser = sysUserMapper.selectById(userId);
        final Integer crawlerFlag = sysUser.getCrawlerFlag();//是否具有爬虫权限


        Page<StationShareDTO> page = new Page<>(stationListPara.getCurrentPage(), stationListPara.getPerPage());
        IPage<StationListDTO> stationListDTOS = null;

        //解析bindlist 赋值bindFlag,unbindFlag
        stationListPara.parseBindList();

        stationListDTOS = sysStationMapper.getStationList(page, stationListPara, stationData, userId, crawlerFlag);
        for (StationListDTO dto : stationListDTOS.getRecords()) {
            QueryWrapper<SysStationEquipment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("station_id", dto.getStationId())
                    .in("mount_status", 1, 2);
            List<SysStationEquipment> stationEquipments = sysStationEquipmentMapper.selectList(queryWrapper);
            List<String> equipmentIds = stationEquipments.stream().map(SysStationEquipment::getEquipmentId).collect(Collectors.toList());
            if (equipmentIds.size() > 0) {
                dto.setMountStatus(1);
                dto.setEquipmentId(String.join(",", equipmentIds));
            }
        }

        //格式化属性,赋值相关属性
        if (stationListDTOS != null && stationListDTOS.getRecords() != null) {
            final List<StationListDTO> records = stationListDTOS.getRecords();
            formartSettingStationList(records, stationData);
        }
        return stationListDTOS;

    }

    /**
     * 数据导出
     *
     * @param stationListPara
     * @param stationIds
     * @param userId
     * @return
     */
    @Override
    public List<StationExportDTO> exportData(StationListPara stationListPara, List<ModelDTO> stationIds, String userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        final Integer crawlerFlag = sysUser.getCrawlerFlag();//是否具有爬虫权限
        //解析bindlist 赋值bindFlag,unbindFlag
        if (stationListPara != null) {
            stationListPara.parseBindList();
        }
        List<StationExportDTO> stationExportDTOS = sysStationMapper.exportData(stationListPara, stationIds, userId, crawlerFlag);
        return stationExportDTOS;
    }

    /**
     * 处理共享时间段
     *
     * @param temp
     * @return
     */
    @Override
    public void hanldShareInfo(List<StationExportDTO> temp) {
        temp.forEach(e -> e.setShareInfo(exportDateTimeDesc(e.getShareDate(), e.getStartTime(), e.getEndTime())));
    }

    /**
     * 格式化属性,赋值相关属性
     *
     * @param records
     * @param stationData
     */
    private void formartSettingStationList(List<StationListDTO> records, List<ModelDTO> stationData) {
        for (StationListDTO record : records) {
            if (record != null) {
                //处理共享时间
                settingShareTime(record);
                //从符合权限的站点里面赋值可读,可写
                settingPermission(stationData, record);
            }
        }
    }

    private void settingShareTime(StationListDTO record) {
        if (record != null) {
            final String shareDate = record.getShareDate();
            final String shareStartTime = record.getShareStartTime();
            final String shareEndTime = record.getShareEndTime();
            record.setShareDateTimeDesc(dateTimeDesc(shareDate, shareStartTime, shareEndTime, true));
            //设置是否处在时间范围内
            final Integer inShareTime = isInShareTime(shareDate, shareStartTime, shareEndTime);
            record.setIsInShareTime(inShareTime);
        }
    }

    /**
     * 从符合权限的站点里面赋值可读,可写
     *
     * @param stationData
     * @param record
     */
    private void settingPermission(List<ModelDTO> stationData, StationListDTO record) {
        if (stationData != null && record != null) {
            for (ModelDTO stationDatum : stationData) {
                if (stationDatum != null && stationDatum.getModelId() != null && stationDatum.getModelId().equalsIgnoreCase(record.getStationId())) {
                    record.setReadAuth(stationDatum.getReadAuth());
                    record.setManageAuth(stationDatum.getManageAuth());
                    break;
                }
            }
        }
    }

    /**
     * 是否处在时间范围内,1为是,0为否
     *
     * @param shareDate
     * @param shareStartTime
     * @param shareEndTime
     * @return
     */
    private Integer isInShareTime(String shareDate, String shareStartTime, String shareEndTime) {
        if (StrUtil.isBlank(shareDate) || StrUtil.isBlank(shareStartTime) || StrUtil.isBlank(shareEndTime)) return 0;
        int inTime = 0;
        final String weekDay = DateUtil.getWeekDay();
        String format = "HH:mm";
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            final Date nowDate = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
            Date startTime = simpleDateFormat.parse(shareStartTime);
            Date endTime = simpleDateFormat.parse(shareEndTime);
            final boolean effectiveDate = DateUtil.isEffectiveDate(nowDate, startTime, endTime);
            if (shareDate.contains(weekDay) && effectiveDate) inTime = 1;//处于当前星期几且时间范围匹配
            else inTime = 0;
        } catch (Exception e) {
            logger.error("是否处于分享时间范围内错误", e);
        }
        return inTime;
    }

    /**
     * 网格化监测点导入
     *
     * @param file
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult stationExcel(MultipartFile file, String userId, String orderId) throws IOException {
        List<SysDomain> proList = sysDomainMapper.getAllDomainDTOById(PROID);
        List<SysDomain> cityList = sysDomainMapper.getAllDomainDTOById(CITYID);
        List<SysDomain> distList = sysDomainMapper.getAllDomainDTOById(DISTID);
        List<SysDictionaryConfig> sysDictionaryConfigs = sysDictionaryConfigMapper.selectByMap(ImmutableMap.of());
        orderId = sysOrderMapper.isDeleteOrderById(orderId);
        if (StrUtil.isBlank(orderId)) {
            return new AjaxResult(WamingConstant.FAILURE, "所选订单不存在！", null);
        }
        //设备种类
        final List<SysDictionaryConfig> sysDictionaryConfigList =
                sysDictionaryConfigs.stream().filter(it -> it.getType() == 7).collect(Collectors.toList());
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysStation> stations = new ArrayList<>();
            List<String> stationIds = new ArrayList<>();
            List<SysEquipment> equipments = new ArrayList<>();
            List<String> equipmentIds = new ArrayList<>();
            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*监测点信息*/
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号不能为空！", null);
                }
                SysStation sysStation = new SysStation();
                if (!CommonUtil.isLetterDigit(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号输入错误！", null);
                }
                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(0)));
                if (stationIds.contains(sysStation.getStationId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
                }
                stationIds.add(sysStation.getStationId());
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列监测点名称不能为空！", null);
                }
                //监测点名称
                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(1)));
                //监测点种类
                String stationCatagory = ExcelUtil.getCellStringValue(row.getCell(2));
                if (StringUtils.isEmpty(stationCatagory)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第3列监测点种类不能为空！", null);
                }
                String stType = ExcelUtil.getCellStringValue(row.getCell(3));
                if (StringUtils.isEmpty(stType)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点类型不能为空！", null);
                }
                //监测点种类
                sysDictionaryConfigList.forEach(it -> {
                    if (it.getName().equals(stationCatagory)) {
                        sysStation.setStationCatagory(Integer.valueOf(it.getCode()));
                        //扬尘类型
                        final List<SysDictionaryConfig> stationType =
                                sysDictionaryConfigs.stream().filter(type -> type.getParent() == it.getId()).collect(Collectors.toList());
                        stationType.forEach(sType -> {
                            if (sType.getName().equals(stType)) {
                                sysStation.setStationType(Integer.valueOf(sType.getCode()));
                            }
                        });
                    }
                });
                String value = ExcelUtil.getCellStringValue(row.getCell(4));
                if (StringUtils.isEmpty(value)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列监测点状态不能为空！", null);
                }
                //监测点状态
                final List<SysDictionaryConfig> stationStatus =
                        sysDictionaryConfigs.stream().filter(it -> it.getType() == 21).collect(Collectors.toList());
                stationStatus.forEach(it -> {
                    if (it.getName().equals(value)) {
                        sysStation.setStatus(Integer.valueOf(it.getCode()));
                    }
                });
                if (sysStation.getStatus() <= 0) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列监测点状态错误！", null);
                }

                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(5)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第6列省份不能为空！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(6)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第7列城市不能为空！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(7)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第8列区县不能为空！", null);
                }
                //省市区
                fillData(row.getCell(5), row.getCell(6), row.getCell(7), null, sysStation, proList, cityList, distList, null);
                //地址
                sysStation.setAddr(ExcelUtil.getCellStringValue(row.getCell(8)));
                //gps经度
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(9)))) {
                    BigDecimal bigDecimal = new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(9)));
                    if (bigDecimal.doubleValue() > 180 || bigDecimal.doubleValue() < -180) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第10列经度错误！", null);
                    }
                    sysStation.setLngReal(bigDecimal);
                }
                //gps纬度
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(10)))) {
                    BigDecimal bigDecimal1 = new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(10)));
                    if (bigDecimal1.doubleValue() > 90 || bigDecimal1.doubleValue() < -90) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第11列纬度错误！", null);
                    }
                    sysStation.setLatReal(bigDecimal1);
                }
                //杆号
                sysStation.setPoleId(ExcelUtil.getCellStringValue(row.getCell(11)));
                //电表号
                sysStation.setAmmeterNo(ExcelUtil.getCellStringValue(row.getCell(12)));
                sysStation.setCreateBy(userId);
                sysStation.setCreateDt(DateUtil.getDateTime(new Date()));
                sysStation.setBusinessType(1);
                sysStation.setWorkType(1);
                sysStation.setShared(2);
                stations.add(sysStation);
                //设备绑定监测点
                String equipmentId = StringUtil.objectString(row.getCell(13));
                if (!StringUtils.isEmpty(equipmentId)) {
                    String order = sysOrderEquipmentMapper.findOrderIdByEquipmentId(equipmentId);
                    if (StrUtil.isNotBlank(order)) {
                        if (!orderId.equals(order)) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第14列设备编号已绑定别的订单！", null);
                        }
                    }
                    if (equipmentIds.contains(equipmentId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + equipmentId + "重复");
                    }
                    equipmentIds.add(equipmentId);
                    SysStationEquipment sysStationEquipment = new SysStationEquipment();
                    sysStationEquipment.setStationId(sysStation.getStationId());
                    sysStationEquipment.setEquipmentId(equipmentId);
                    sysStationEquipment.setMountStatus(1);
                    sysStationEquipment.setIsLast(1);
                    sysStationEquipment.setOperateBy(userId);
                    sysStationEquipment.setBindTime(DateUtil.getDateTime(new Date()));
                    sysStationEquipments.add(sysStationEquipment);
                    /*设备信息*/
                    String status = ExcelUtil.getCellStringValue(row.getCell(14));
                    if (!StringUtils.isEmpty(status)) {
                        SysEquipment sysEquipment = new SysEquipment();
                        sysEquipment.setEquipmentId(equipmentId);
                        //监测点状态
                        final List<SysDictionaryConfig> equipmentStatus =
                                sysDictionaryConfigs.stream().filter(it -> it.getType() == 4).collect(Collectors.toList());
                        equipmentStatus.forEach(it -> {
                            if (it.getName().equals(status)) {
                                sysEquipment.setStatus(Integer.valueOf(it.getCode()));
                            }
                        });
                        if (sysEquipment.getStatus() <= 0) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第15列设备状态错误！", null);
                        }
                        equipments.add(sysEquipment);
                    }
                }
                //订单绑定设备信息
                EquipmentBO sysOrderEquipment = new EquipmentBO();
                sysOrderEquipment.setOrderId(orderId);
                sysOrderEquipment.setStationId(sysStation.getStationId());
                if (!StringUtils.isEmpty(equipmentId)) {
                    sysOrderEquipment.setEquipmentId(equipmentId);
                }
                sysOrderEquipment.setCreateBy(userId);
                sysOrderEquipments.add(sysOrderEquipment);
            }
            //验证设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = updateEquipmentStatus(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //添加监测点
            List<String> Ids = new ArrayList<>();
            if (stations.size() > 0) {
                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //验证导入设备是否已经绑定设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //修改设备状态
            if (equipments.size() > 0) {
                for (SysEquipment sysEquipment : equipments) {
                    sysEquipmentMapper.updateEquipmentByEquipmentId(sysEquipment.getEquipmentId(), sysEquipment.getStatus());
                }
            }
            if (stations.size() > 0) {
                sysStationMapper.deleteStations(stations);
                //添加监测点
                sysStationMapper.insertStations(stations);

            }
            //绑定设备和监测点，绑定订单和设备
            relieveBuildling(sysStationEquipments, sysOrderEquipments, Ids, orderId);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

    /**
     * 健康空气监测点导入
     *
     * @param file
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult stationExcelJKKQ(MultipartFile file, String userId, String orderId) throws IOException {
        List<SysDomain> proList = sysDomainMapper.getAllDomainDTOById(PROID);
        List<SysDomain> cityList = sysDomainMapper.getAllDomainDTOById(CITYID);
        List<SysDomain> distList = sysDomainMapper.getAllDomainDTOById(DISTID);
        List<SysDomain> streetList = sysDomainMapper.getAllDomainDTOById(STREET);
        List<SysDictionaryConfig> sysDictionaryConfigs = sysDictionaryConfigMapper.selectByMap(ImmutableMap.of());
        orderId = sysOrderMapper.isDeleteOrderById(orderId);
        if (StrUtil.isBlank(orderId)) {
            return new AjaxResult(WamingConstant.FAILURE, "所选订单不存在！", null);
        }
        //设备种类
        final List<SysDictionaryConfig> sysDictionaryConfigList =
                sysDictionaryConfigs.stream().filter(it -> it.getType() == 14).collect(Collectors.toList());
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysStation> stations = new ArrayList<>();
            List<String> stationIds = new ArrayList<>();
            /*List<SysEquipment> sysEquipments = new ArrayList<>();*/
            List<String> equipmentIds = new ArrayList<>();
            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*监测点信息*/
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号不能为空！", null);
                }
                SysStation sysStation = new SysStation();
                //监测点编号
                if (!CommonUtil.isLetterDigit(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号输入错误！", null);
                }
                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(0)));
                if (stationIds.contains(sysStation.getStationId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
                }
                stationIds.add(sysStation.getStationId());
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列监测点名称不能为空！", null);
                }
                //监测点名称
                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(1)));
                sysStation.setStationNameEn(ExcelUtil.getCellStringValue(row.getCell(2)));
                //监测点种类
                String sTechType = ExcelUtil.getCellStringValue(row.getCell(3));
                if (StringUtils.isEmpty(sTechType)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第3列监测点种类不能为空！", null);
                }
                //监测点种类
                sysDictionaryConfigList.forEach(it -> {
                    if (it.getName().equals(sTechType)) {
                        sysStation.setStationCatagory(Integer.valueOf(it.getCode()));
                    }
                });
                if (sysStation.getStationCatagory() == null || sysStation.getStationCatagory() <= 0) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第3列监测点种类不正确！", null);
                }
                String value = ExcelUtil.getCellStringValue(row.getCell(4));
                if (StringUtils.isEmpty(value)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点状态不能为空！", null);
                }
                //监测点状态
                final List<SysDictionaryConfig> stationStatus =
                        sysDictionaryConfigs.stream().filter(it -> it.getType() == 18).collect(Collectors.toList());
                stationStatus.forEach(it -> {
                    if (it.getName().equals(value)) {
                        sysStation.setStatus(Integer.valueOf(it.getCode()));
                    }
                });
                if (sysStation.getStatus() <= 0) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点状态错误！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(5)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列省份不能为空！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(6)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第6列城市不能为空！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(7)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第7列区县不能为空！", null);
                }
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(8)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第8列街道不能为空！", null);
                }
                //省市区
                String streetName = fillData(row.getCell(5), row.getCell(6), row.getCell(7), row.getCell(8), sysStation, proList, cityList,
                        distList, streetList);
//                //地址
//                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(9)))) {
//                    sysStation.setAddr(ExcelUtil.getCellStringValue(row.getCell(9)));
//                    //return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第9列地址不能为空！", null);
//                }
                //gps经度
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(9)))) {
                    BigDecimal bigDecimal = new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(9)));
                    if (bigDecimal.doubleValue() > 180 || bigDecimal.doubleValue() < -180) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第9列经度错误！", null);
                    }
                    sysStation.setLngReal(bigDecimal);
                }
                //gps纬度
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(10)))) {
                    BigDecimal bigDecimal1 = new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(10)));
                    if (bigDecimal1.doubleValue() > 90 || bigDecimal1.doubleValue() < -90) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第10列纬度错误！", null);
                    }
                    sysStation.setLatReal(bigDecimal1);
                }
//                //空间
//                String building = ExcelUtil.getCellStringValue(row.getCell(11));
//                if (StringUtils.isEmpty(building)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第12列楼宇不能为空！", null);
//                }
//                String floor = ExcelUtil.getCellStringValue(row.getCell(12));
//                if (StringUtils.isEmpty(floor)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列楼层不能为空！", null);
//                }
//                String room = ExcelUtil.getCellStringValue(row.getCell(13));
//                if (StringUtils.isEmpty(room)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列房间不能为空！", null);
//                }
//                setBuildMo(streetName, null, null, null, sysStation);
                sysStation.setCreateBy(userId);
                sysStation.setBusinessType(1);
                sysStation.setWorkType(2);
                sysStation.setShared(2);
                sysStation.setCreateDt(DateUtil.getDateTime(new Date()));
                stations.add(sysStation);
                //设备绑定监测点
                String equipmentId = ExcelUtil.getCellStringValue(row.getCell(11));
                if (!StringUtils.isEmpty(equipmentId)) {
                    String order = sysOrderEquipmentMapper.findOrderIdByEquipmentId(equipmentId);
                    if (StrUtil.isNotBlank(order)) {
                        if (!orderId.equals(order)) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第11列设备编号已绑定别的订单！", null);
                        }
                    }
                    if (equipmentIds.contains(equipmentId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + equipmentId + "重复");
                    }
                    equipmentIds.add(equipmentId);
                    SysStationEquipment sysStationEquipment = new SysStationEquipment();
                    sysStationEquipment.setStationId(sysStation.getStationId());
                    sysStationEquipment.setEquipmentId(equipmentId);
                    sysStationEquipment.setMountStatus(1);
                    sysStationEquipment.setIsLast(1);
                    sysStationEquipment.setOperateBy(userId);
                    sysStationEquipment.setBindTime(DateUtil.getDateTime(new Date()));
                    sysStationEquipments.add(sysStationEquipment);
                    /*设备信息*/
                    /*String status = ExcelUtil.getCellStringValue(row.getCell(15));
                    if (!StringUtils.isEmpty(status)) {
                        SysEquipment sysEquipment = new SysEquipment();
                        sysEquipment.setEquipmentId(equipmentId);
                        //监测点状态
                        final List<SysDictionaryConfig> equipmentStatus =
                                sysDictionaryConfigs.stream().filter(it -> it.getType() == 4).collect(Collectors.toList());
                        equipmentStatus.forEach(it -> {
                            if (it.getName().equals(status)) {
                                sysEquipment.setStatus(Integer.valueOf(it.getCode()));
                            }
                        });
                        if (sysEquipment.getStatus() <= 0) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第16列设备状态错误！", null);
                        }
                        sysEquipments.add(sysEquipment);
                    }*/
                }
                //订单绑定设备
                EquipmentBO sysOrderEquipment = new EquipmentBO();
                sysOrderEquipment.setOrderId(orderId);
                sysOrderEquipment.setStationId(sysStation.getStationId());
                if (!StringUtils.isEmpty(equipmentId)) {
                    sysOrderEquipment.setEquipmentId(equipmentId);
                }
                sysOrderEquipment.setCreateBy(userId);
                sysOrderEquipments.add(sysOrderEquipment);
            }
            //验证设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = updateEquipmentStatus(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //添加监测点
            List<String> Ids = new ArrayList<>();
            if (stations.size() > 0) {
                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //验证导入监测点是否已经绑定设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //修改设备状态
            /*if (sysEquipments.size() > 0) {
                for (SysEquipment sysEquipment : sysEquipments) {
                    sysEquipmentMapper.updateEquipmentByEquipmentId(sysEquipment.getEquipmentId(), sysEquipment.getStatus());
                }
            }*/
            if (stations.size() > 0) {
                sysStationMapper.deleteStations(stations);
                //添加监测点
                sysStationMapper.insertStations(stations);
            }
            //绑定设备和监测点，绑定订单和监测点
            relieveBuildling(sysStationEquipments, sysOrderEquipments, Ids, orderId);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

    public void setBuildMo(String streetName, String building, String floor, String room, SysStation sysStation) {
        Integer domainId = null;
        if (sysStation.getDistrict() != null) {
            domainId = sysStation.getDistrict();
        } else {
            if (sysStation.getCity() != null) {
                domainId = sysStation.getCity();
            } else {
                if (sysStation.getPro() != null) {
                    domainId = sysStation.getPro();
                }
            }
        }
        String moId = moHandler(String.valueOf(domainId), streetName, building, floor, room);
        sysStation.setMoId(moId);
    }

    public List<SysStationMoDTO> setMoMap(List<SysStationMoDTO> stationMos) {
        //按父菜单分类
        Map<String, List<SysStationMoDTO>> funcMap =
                stationMos.stream().filter(it -> it.getParentId() != null).collect(Collectors.groupingBy(SysStationMoDTO::getParentId));
        //有子菜单的设置子菜单
        stationMos.stream().filter(it -> funcMap.keySet().contains(it.getId())).forEach(it -> {
            it.setChildrenMoDTOs(funcMap.get(it.getId()).stream().collect(Collectors.toList()));
        });
        //将第一级菜单返回
        List<SysStationMoDTO> menuDTOList = stationMos.stream().filter(it -> StringUtils.isEmpty(it.getParentId())).collect(Collectors.toList());
        return menuDTOList;
    }

    /**
     * 批量更新设备状态并验证设备是否存在
     */
    public AjaxResult updateEquipmentStatus(List<SysStationEquipment> sysStationEquipments) {
        List<String> eqIds = new ArrayList<>();
        sysStationEquipments.stream().forEach(it -> {
            eqIds.add(it.getEquipmentId());
        });
        List<String> equipmentIds = sysEquipmentMapper.findEquipments(eqIds);
        if (eqIds.size() != equipmentIds.size()) {
            for (String equipmentId : equipmentIds) {
                if (eqIds.contains(equipmentId)) {
                    eqIds.remove(equipmentId);
                }
            }
            String equipmenIdJson = StringUtil.listToString(eqIds);
            return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在");
        }
        return null;
    }

    /**
     * 验证监测点是否已经存在及插入监测点
     *
     * @param sysStations
     * @return
     */
    public AjaxResult stationVerifyExistence(List<SysStation> sysStations, List<String> Ids, String orderId) {
        sysStations.stream().forEach(it -> {
            Ids.add(it.getStationId());
        });
        //验证设备是否绑定其他订单
        List<String> count = sysOrderEquipmentMapper.verifyEquipmentOrderId(orderId, null, Ids);
        if (count.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(count);
            return new AjaxResult(WamingConstant.FAILURE, "监测点" + equipmenIdJson + "已绑定其他订单");
        }
        List<String> equipmentIds = sysStationMapper.findStations(Ids);
        if (equipmentIds.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(equipmentIds);
            return new AjaxResult(WamingConstant.FAILURE, "监测点" + equipmenIdJson + "已经存在");
        }
        return null;
    }

    public AjaxResult checkStationEquipment(List<SysStationEquipment> sysStationEquipments) {
        //验证设备与监测的绑定关系
        List<SysStationEquipment> stationEquipments = sysStationEquipmentMapper.findStationEquipments(sysStationEquipments);
        if (stationEquipments.size() > 0) {
            String equipmenIdJson = StringUtil.objectToString(stationEquipments);
            return new AjaxResult(WamingConstant.FAILURE, equipmenIdJson + "已经绑定");
        }
        return null;
    }

    /**
     * 绑定设备和监测点，绑定订单和监测点
     *
     * @param sysStationEquipments
     * @param eqIds
     */
    public void relieveBuildling(List<SysStationEquipment> sysStationEquipments, List<EquipmentBO> sysOrderEquipments, List<String> eqIds,
                                 String orderId) {
        sysStationEquipmentMapper.deleteStationEquipmentsByStationId(eqIds);
        if (sysStationEquipments.size() > 0) {
            //批量解除设备与检测的绑定关系
            sysStationEquipmentMapper.deleteStationEquipments(sysStationEquipments);
            //建立设备与检测的绑定关系
            sysStationEquipmentMapper.insertStationEquipments(sysStationEquipments);
            Map<String, String> stationMap = new HashMap<>();
            Map<String, String> equipmentMap = new HashMap<>();
            sysStationEquipments.stream().forEach(it -> {
                stationMap.put(it.getStationId(), it.getEquipmentId());
                equipmentMap.put(it.getEquipmentId(), it.getStationId());
            });
            //查询设备与设备组绑定关系
            List<SysStationGroupEquipment> list = sysStationGroupEquipmentMapper.findStationGroupEquipment(sysStationEquipments);
            if (list.size() > 0) {
                //删除设备与设备组绑定关系
                sysStationGroupEquipmentMapper.deleteStationGroupEquipment(list);
                list.stream().forEach(it -> {
                    if (StringUtils.isEmpty(it.getEquipmentId())) {
                        it.setEquipmentId(stationMap.get(it.getStationId()));
                    }
                    if (StringUtils.isEmpty(it.getStationId())) {
                        it.setStationId(equipmentMap.get(it.getEquipmentId()));
                    }
                });
                //添加设备与设备组绑定关系
                sysStationGroupEquipmentMapper.insertStationGroupEquipment(list);
            }
        }
        sysOrderEquipmentMapper.deleteOrderByStationId(eqIds);
        if (sysOrderEquipments.size() > 0) {
            //删除订单已经绑定的设备，避免重复绑定
            sysOrderEquipmentMapper.deleteEquipmentsByStationIds(orderId, sysOrderEquipments);
            //添加订单和设备的绑定
            sysOrderEquipmentMapper.orderToEquipment(sysOrderEquipments);
        }
    }

    /**
     * 插入省市区
     */
    private String fillData(Cell cell1, Cell cell2, Cell cell3, Cell cell4, SysStation sysStation, List<SysDomain> proList,
                            List<SysDomain> cityList, List<SysDomain> distList, List<SysDomain> streetList) {
        // 此处进行赋值
        // wwPollutionsRepo.setId(row.getCell(0).toString());//省
        String proName = ExcelUtil.getCellStringValue(cell1);
        String cityName = ExcelUtil.getCellStringValue(cell2);
        String distName = ExcelUtil.getCellStringValue(cell3);
        String streetName = ExcelUtil.getCellStringValue(cell4);
        if (StrUtil.isNotBlank(proName)) {
            Long proid = null;
            for (SysDomain pro : proList) {
                if (pro.getDomainName().equalsIgnoreCase(proName.trim())) {
                    proid = pro.getId();
                    sysStation.setPro(Integer.parseInt(StringUtil.objectString(proid)));
                    break;
                }
            }
            if (proid != null && StrUtil.isNotBlank(cityName)) {
                Long cityId = null;
                for (SysDomain city : cityList) {
                    if (city.getDomainName().equalsIgnoreCase(cityName.trim()) && proid.equals(city.getParentId())) {
                        cityId = city.getId();
                        sysStation.setCity(Integer.parseInt(StringUtil.objectString(cityId)));
                        break;
                    }
                }
                if (StrUtil.isNotBlank(distName) && cityId != null) {
                    Long distId = null;
                    for (SysDomain dist : distList) {
                        if (dist.getDomainName().equalsIgnoreCase(distName.trim()) && cityId.equals(dist.getParentId())) {
                            distId = dist.getId();
                            sysStation.setDistrict(Integer.parseInt(String.valueOf(dist.getId())));
                            break;
                        }
                    }
                    if (StrUtil.isNotBlank(streetName) && distId != null) {
                        for (SysDomain street : streetList) {
                            if (street.getDomainName().equalsIgnoreCase(streetName.trim()) && distId.equals(street.getParentId())) {
                                sysStation.setStreet(street.getId());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return streetName;
    }

    private List<String> getOrderList(List<String> orgids) {

        return null;
    }

    private int insert(AddStationDTO addStationDTO, String userId, SysStation station) {
        station.setCreateBy(userId);
        station.setCreateDt(DateUtil.getCurrentDateTime());
        station.setModifyBy(userId);
        station.setModifyDt(DateUtil.getCurrentDateTime());
        station.setBusinessType(1);
        int insert = sysStationMapper.insert(station);
        if (insert > 0) {
            /*插入图片*/
            List<String> imgUrls = addStationDTO.getImgUrls();
            if (CollUtil.isNotEmpty(imgUrls)) {
                for (int i = 0; i < imgUrls.size(); i++) {
                    SysStationImages imgs = new SysStationImages();
                    imgs.setId(UUID.randomUUID().toString().replace("-", ""));
                    imgs.setStationId(addStationDTO.getStationId());
                    imgs.setImageUrl(imgUrls.get(i));
                    imgs.setOrderSn(i);
                    imgs.setDirection("ASC");
                    sysStationImagesMapper.insert(imgs);
                }
            }
            //插入共享信息
            List<String> shareDates = addStationDTO.getShareDates();
            SysStationShareTime ssst = new SysStationShareTime();
            ssst.setStationId(addStationDTO.getStationId());
            ssst.setShareDate(String.join(",", shareDates));
            ssst.setStartTime(addStationDTO.getStartTime());
            ssst.setEndTime(addStationDTO.getEndTime());
            ssst.setCreateBy(userId);
            ssst.setCreateDt(new Date());
            sysStationShareTimeMapper.insert(ssst);

            //绑定设备
            String equipmentId = addStationDTO.getEquipmentId();
            if (StrUtil.isNotBlank(equipmentId)) {
                SysStationEquipment sse = new SysStationEquipment();
                sse.setStationId(addStationDTO.getStationId());
                sse.setBindTime(DateUtil.getCurrentDateTime());
                sse.setOperateBy(userId);
                sse.setMountStatus(WamingConstant.ONE);
                sse.setEquipmentId(equipmentId);
                sysStationEquipmentMapper.insert(sse);
            }
            //添加订单检测点关系
            if (StrUtil.isNotBlank(addStationDTO.getOrderId())) {
                SysOrderEquipment soe = new SysOrderEquipment();
                soe.setStationId(addStationDTO.getStationId());
                soe.setOrderId(addStationDTO.getOrderId());
                soe.setEquipmentId(addStationDTO.getEquipmentId());
                soe.setCreateBy(userId);
                soe.setCreateDt(new Date());
                soe.setModifyBy(userId);
                soe.setModifyDt(new Date());
                sysOrderEquipmentMapper.insert(soe);
            }

        }
        return insert;
    }

    private int update(AddStationDTO addStationDTO, String userId, SysStation station) {
        station.setId(addStationDTO.getId());
        station.setModifyBy(userId);
        station.setModifyDt(DateUtil.getCurrentDateTime());
        //更新监测点主表数据
        int update = sysStationMapper.updateById(station);
        if (update > 0) {
            //删除所有的图片，重新添加
            sysStationImagesMapper.deleteByMap(ImmutableMap.of("station_id", addStationDTO.getStationId()));
            List<String> imgUrls = addStationDTO.getImgUrls();
            if (CollUtil.isNotEmpty(imgUrls)) {
                for (int i = 0; i < imgUrls.size(); i++) {
                    SysStationImages imgs = new SysStationImages();
                    imgs.setId(UUID.randomUUID().toString().replace("-", ""));
                    imgs.setStationId(addStationDTO.getStationId());
                    imgs.setImageUrl(imgUrls.get(i));
                    imgs.setOrderSn(i);
                    imgs.setDirection("ASC");
                    sysStationImagesMapper.insert(imgs);
                }
            }
            // sysOrderEquipmentMapper.deleteByMap(ImmutableMap.of("station_id", addStationDTO.getStationId()));
            //删除共享信息
            sysStationShareTimeMapper.deleteByMap(ImmutableMap.of("station_id", addStationDTO.getStationId()));
            //插入共享信息

            SysStationShareTime ssst = new SysStationShareTime();
            ssst.setStationId(addStationDTO.getStationId());
            List<String> shareDates = addStationDTO.getShareDates();
            if (CollUtil.isEmpty(shareDates)) {
                ssst.setShareDate("");
            } else {
                ssst.setShareDate(String.join(",", shareDates));
            }
            ssst.setStartTime(addStationDTO.getStartTime());
            ssst.setEndTime(addStationDTO.getEndTime());
            ssst.setCreateBy(userId);
            ssst.setCreateDt(new Date());
            sysStationShareTimeMapper.insert(ssst);

            //监测点订单数据处理
            QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
            query.eq("station_id", addStationDTO.getStationId());
            SysOrderEquipment orderEquipment = sysOrderEquipmentMapper.selectOne(query);
            String oldOrderId = null;
            if (Objects.nonNull(orderEquipment)) {
                oldOrderId = orderEquipment.getOrderId();
            }
            String newOrderId = addStationDTO.getOrderId();
            //如果修改了所属订单，并且导致订单关联的客户发生了变化，那么将此监测点从原有的客户下的所有的设备组中清除掉。
            if (StrUtil.isNotBlank(oldOrderId) && StrUtil.isNotBlank(newOrderId) && !oldOrderId.equals(newOrderId)) {
                //修改订单监测点关系
                SysOrderEquipment soe = new SysOrderEquipment();
                soe.setStationId(addStationDTO.getStationId());
                soe.setOrderId(newOrderId);
                soe.setEquipmentId(addStationDTO.getEquipmentId());
                soe.setModifyBy(userId);
                soe.setModifyDt(new Date());
                QueryWrapper<SysOrderEquipment> oeq = new QueryWrapper();
                oeq.eq("station_id", addStationDTO.getStationId());
                sysOrderEquipmentMapper.update(soe, oeq);
                //老客户
                SysOrder oldOrder = sysOrderMapper.findOrderById(oldOrderId);
                //新客户
                SysOrder newOrder = sysOrderMapper.findOrderById(newOrderId);
                if (oldOrder != null && newOrder != null && !oldOrder.getOrgId().equals(newOrder.getOrgId())) {
                    //将此监测点从原有的客户下的所有的设备组中清除掉
                    List<SysOrgStationGroup> orgStationGroups = sysOrgStationGroupMapper.selectByMap(ImmutableMap.of("org_id", oldOrder.getOrgId()));
                    orgStationGroups.forEach(os -> {
                        sysStationGroupEquipmentMapper.deleteByMap(ImmutableMap.of("group_id", os.getGroupId(), "station_id",
                                addStationDTO.getStationId()));
                    });
                }
            }
            //原来没有订单的情况，新分配了订单
            if (StrUtil.isBlank(oldOrderId) && StrUtil.isNotBlank(newOrderId)) {
                SysOrderEquipment soe = new SysOrderEquipment();
                soe.setStationId(addStationDTO.getStationId());
                soe.setOrderId(newOrderId);
                soe.setEquipmentId(addStationDTO.getEquipmentId());
                soe.setCreateBy(userId);
                soe.setCreateDt(new Date());
                soe.setModifyBy(userId);
                soe.setModifyDt(new Date());
                sysOrderEquipmentMapper.insert(soe);
            }
        }
        return update;
    }

    /**
     * 根据监控对象的名字操作监控对象
     *
     * @param build
     * @param floor
     * @param room
     * @return
     */
    private String moHandler(String domainId, String streetName, String build, String floor, String room) {
        if (StrUtil.isBlank(StrUtil.trim(build)) || StrUtil.isBlank(StrUtil.trim(streetName))
                || StrUtil.isBlank(StrUtil.trim(floor)) || StrUtil.isBlank(StrUtil.trim(room))) {
            return StrUtil.EMPTY;
        }
        String roadId = sysStationMoMapper.getRoadId(streetName, domainId);
        String rId;
        if (StrUtil.isBlank(roadId)) {
            //全新的街道，则楼宇和楼层和房间都是最新的
            rId = moByInexistenceRoad(domainId, streetName, build, floor, room);
        } else {
            //根据楼宇名称来匹配
            rId = moByExistRoad(domainId, streetName, build, floor, room);
        }
        //添加默认的预警配置 update   2020-04-15
//        String shipId = rId.substring(0, 5);
//        QueryWrapper<TdWcenterThreshold> query = new QueryWrapper<>();
//        query.eq("project_id", shipId);
//        Integer count = thresholdMapper.selectCount(query);
//        if (count == null || count <= 0) {
//            //没有，则插入默认配置
//            List<TdWcenterThresholdDefault> defaults = thresholdDefaultMapper.selectList(new QueryWrapper<>());
//            defaults.forEach(e -> {
//                TdWcenterThreshold threshold = new TdWcenterThreshold();
//                BeanUtil.copyProperties(e, threshold);
//                threshold.setProjectId(shipId);
//                threshold.setTime(LocalDateTime.now());
//                thresholdMapper.insert(threshold);
//            });
//        }
        return rId;
    }

    /**
     * 当该区域的街道是存在的实时，对MO对象的操作(都是全新的操作)
     *
     * @param domainId
     * @param streetName
     * @param build
     * @param floor
     * @param room
     * @return
     */
    private String moByInexistenceRoad(String domainId, String streetName, String build, String floor, String room) {
        //插入道路信息
        String roadId = insertRoad(streetName);
        //插入楼宇
        Long maxBuildId = sysStationMoMapper.findMaxBuildId();
        SysStationMo b = new SysStationMo();
        String bid = String.valueOf(maxBuildId + 1);
        b.setId(bid);
        b.setCapation(StrUtil.trim(build));
        b.setMoType(1);
        b.setOrderBy(0);
        b.setDomainId(domainId);
        b.setAddress(roadId);
        sysStationMoMapper.insert(b);
        //插入楼层
        SysStationMo f = new SysStationMo();
        String fid = bid.concat("10000");
        f.setId(fid);
        f.setParentId(bid);
        f.setCapation(StrUtil.trim(floor));
        f.setMoType(2);
        f.setOrderBy(0);
        f.setDomainId(domainId);
        sysStationMoMapper.insert(f);
        //插入房间
        SysStationMo r = new SysStationMo();
        String rid = fid.concat("10000");
        r.setId(rid);
        r.setParentId(fid);
        r.setCapation(StrUtil.trim(room));
        r.setMoType(3);
        r.setOrderBy(0);
        r.setDomainId(domainId);
        sysStationMoMapper.insert(r);
        return rid;
    }

    /**
     * 当该区域的街道是存在的实时，对MO对象的操作（MO对象不存在的就添加，存在的就对应上）
     *
     * @param domainId
     * @param streetName
     * @param build
     * @param floor
     * @param room
     * @return
     */
    private String moByExistRoad(String domainId, String streetName, String build, String floor, String room) {
        SysStationMo buildMo = sysStationMoMapper.findIdByCapation(StrUtil.trim(build), null, domainId);
        if (buildMo == null) {
            //楼宇为空,创建楼宇，楼层，房间
            Long maxBuildId = sysStationMoMapper.findMaxBuildId();
            SysStationMo b = new SysStationMo();
            String bid = String.valueOf(maxBuildId + 1);
            b.setId(bid);
            b.setCapation(StrUtil.trim(build));
            b.setMoType(1);
            b.setOrderBy(0);
            b.setDomainId(domainId);
            handleRoad(streetName, b, domainId);
            sysStationMoMapper.insert(b);
            String fid = "";
            if (StrUtil.isNotBlank(StrUtil.trim(floor))) {
                SysStationMo f = new SysStationMo();
                fid = bid.concat("10000");
                f.setId(fid);
                f.setParentId(bid);
                f.setCapation(StrUtil.trim(floor));
                f.setMoType(2);
                f.setOrderBy(0);
                f.setDomainId(domainId);
                sysStationMoMapper.insert(f);
            }
            String rid = "";
            if (StrUtil.isNotBlank(fid) && StrUtil.isNotBlank(StrUtil.trim(room))) {
                SysStationMo r = new SysStationMo();
                rid = fid.concat("10000");
                r.setId(rid);
                r.setParentId(fid);
                r.setCapation(StrUtil.trim(room));
                r.setMoType(3);
                r.setOrderBy(0);
                r.setDomainId(domainId);
                sysStationMoMapper.insert(r);
            }
            if (StrUtil.isNotBlank(rid)) {
                return rid;
            } else if (StrUtil.isBlank(rid) && StrUtil.isNotBlank(fid)) {
                return fid;
            } else if (StrUtil.isBlank(rid) && StrUtil.isBlank(fid) && StrUtil.isNotBlank(bid)) {
                return bid;
            }
        } else {
            String bid = buildMo.getId();
            handleRoad(streetName, buildMo, domainId);
            sysStationMoMapper.updateById(buildMo);
            //楼宇存在
            if (StrUtil.isBlank(StrUtil.trim(floor))) {
                return bid;
            } else {
                SysStationMo floorMo = sysStationMoMapper.findIdByCapation(StrUtil.trim(floor), bid, domainId);
                //查看楼宇下是否包含该名字的楼层
                Integer sub = sysStationMoMapper.findSub(bid, StrUtil.trim(floor), domainId);
                if (sub > 0) {
                    //该楼宇下此楼层存在,检测 房间是否存在
                    if (StrUtil.isBlank(StrUtil.trim(room))) {
                        return floorMo.getId();
                    } else {
                        SysStationMo roomMO = sysStationMoMapper.findIdByCapation(StrUtil.trim(room), floorMo.getId(), domainId);
                        Integer rom = sysStationMoMapper.findSub(floorMo.getId(), StrUtil.trim(room), domainId);
                        if (rom > 0) {
                            //该楼层此房间存在
                            return roomMO.getId();
                        } else {
                            //添加该房间
                            SysStationMo r = new SysStationMo();
                            Long maxRoomId = sysStationMoMapper.findMaxRoomId(floorMo.getId());
                            String roomId;
                            if (maxRoomId == null) {
                                roomId = floorMo.getId().concat("10000");
                            } else {
                                roomId = floorMo.getId().concat(String.valueOf(maxRoomId + 1));
                            }
                            r.setId(roomId);
                            r.setParentId(floorMo.getId());
                            r.setCapation(StrUtil.trim(room));
                            r.setMoType(3);
                            r.setOrderBy(0);
                            r.setDomainId(domainId);
                            sysStationMoMapper.insert(r);
                            return roomId;
                        }
                    }
                } else {
                    //添加该楼层
                    SysStationMo f = new SysStationMo();
                    Long maxFloorId = sysStationMoMapper.findMaxFloorId(bid);
                    String floorId;
                    if (maxFloorId == null) {
                        floorId = bid.concat("10000");
                    } else {
                        floorId = bid.concat(String.valueOf(maxFloorId + 1));
                    }
                    f.setId(floorId);
                    f.setParentId(bid);
                    f.setCapation(StrUtil.trim(floor));
                    f.setMoType(2);
                    f.setOrderBy(0);
                    f.setDomainId(domainId);
                    sysStationMoMapper.insert(f);
                    //添加房间
                    SysStationMo r = new SysStationMo();
                    String rommId = floorId.concat("10000");
                    r.setId(rommId);
                    r.setParentId(floorId);
                    r.setCapation(StrUtil.trim(room));
                    r.setMoType(3);
                    r.setOrderBy(0);
                    r.setDomainId(domainId);
                    sysStationMoMapper.insert(r);
                    return rommId;
                }
            }
        }
        return "false";
    }

    /**
     * 出来道路与楼宇的关系
     *
     * @param streetName
     * @param buildMo
     */
    private void handleRoad(String streetName, SysStationMo buildMo, String domainId) {
        if (StrUtil.isNotBlank(streetName)) {
            // String id = sysStationMoAddressMapper.findIdByCapation(StrUtil.trim(streetName),domainId);
            String roadId = sysStationMoMapper.getRoadId(streetName, domainId);
            if (StrUtil.isBlank(roadId)) {
                //插入街道
                String newId = insertRoad(streetName);
                buildMo.setAddress(newId);
            } else {
                buildMo.setAddress(roadId);
            }
        }
    }

    /**
     * 新增道路信息
     *
     * @param streetName
     * @return
     */
    private String insertRoad(String streetName) {
        String newId = UUID.randomUUID().toString().replaceAll("-", "");
        SysStationMoAddress temp = new SysStationMoAddress();
        temp.setId(newId);
        temp.setCapation(StrUtil.trim(streetName));
        sysStationMoAddressMapper.insert(temp);
        return newId;
    }

    /**
     * 根据订单编号查询监测点信息
     *
     * @param orderId      订单编号
     * @param businessType 业务种类
     * @return
     */
    @Override
    public List<StationProjectInfoDTO> findByOrder(String orderId, Integer businessType) {
        return sysStationMapper.findByOrder(orderId, businessType);
    }

    /**
     * 查询监测点的订单信息
     */
    @Override
    public List<StationProjectInfoDTO> findStationOrder(Set<String> stationIdSet) {
        return sysStationMapper.findStationOrderInfo(stationIdSet);
    }

    /**
     * 监测点需要同步的信息查询
     *
     * @param businessType 业务种类
     * @return
     */
    @Override
    public List<StationSyncDTO> findStationSyncInfo(Integer businessType) {
        return sysStationMapper.findStationSyncInfo(businessType);
    }

    /**
     * 监测点绑定信息
     */
    @Override
    public List<StationBindDTO> findStationBindSync(Set<String> stationIdSet) {
        return sysStationMapper.findStationBindSync(stationIdSet);
    }

}
